package com.lzx.orderserver.utils;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

/**
 * @author 刘正星
 * @version v1.0
 * @package com.lzx.orderserver.utils
 * @data 2022/9/14 0:14
 */

public class GenericsUtils {
    /**
     * 通过反射,获得定义Class时声明的父类的范型参数的类型
     *
     * @param clazz
     * @return 返回第一个类型
     */
    public static Class getSuperClassGenricType(Class clazz) {
        return getSuperClassGenricType(clazz, 0);
    }

    /**
     * 通过反射,获得定义Class时声明的父类的范型参数的类型
     *
     * @param clazz
     * @param 返回某下标的类型
     */
    public static Class getSuperClassGenricType(Class clazz, int index)
            throws IndexOutOfBoundsException {
//        Type genType = clazz.getGenericSuperclass();
        Type[] genericInterfaces = clazz.getGenericInterfaces();
//        Type genType = (Type) genericInterfaces;
//        if (!(genType instanceof ParameterizedType)) {
//            return Object.class;
//        }
//        Type[] params = ((ParameterizedType) genType).getActualTypeArguments();
//        if (index >= params.length || index < 0) {
//            return Object.class;
//        }
//        if (!(params[index] instanceof Class)) {
//            return Object.class;
//        }
//        return (Class) params[index];
        if (clazz.getName().contains("CGLIB")) {
            genericInterfaces = clazz.getSuperclass().getGenericInterfaces();
        }
        Type jobType = genericInterfaces[0];
        // 获取泛型接口的泛型参数
        Type type = ((ParameterizedType) jobType).getActualTypeArguments()[0];
        if (!(type instanceof Class)) {
            throw new RuntimeException("Missing type parameter.");
        }
        return (Class) type;
    }
}
